package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.PostDubbleEvent;
import com.jackrain.nea.common.PostHandleEvent;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.common.QueryUserUtil;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.dl.common.utils.esutil.ConvertQueryListUtil;
import com.jackrain.nea.dl.common.utils.esutil.ElasticsearchUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsOrderInSaveCmd;
import com.jackrain.nea.fc.dl.mapper.WmsOrderInMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

/**
 * 采购入库->FC
 * @author xuxinshuai
 * @date 2018/05/05
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsOrderInSaveCmdImpl extends CommandAdapter implements WmsOrderInSaveCmd {

    @Autowired
    PostDubbleEvent postDubbleEvent;

    @Autowired
    PostHandleEvent postHandleEvent;

    @Autowired
    QueryCpUtil postQueryEvemt;

    @Autowired
    QueryUserUtil postUserEvent;

    @Autowired
    private ElasticsearchUtil esUtil;

    @Autowired
    private ConvertQueryListUtil convertQLUtil;

    @Autowired
    private PropertiesConf pconf;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0 || param.getJSONArray("data").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }
//        log.debug("----------入库回传（采购入库）----------");
        log.info("WmsOrderInSaveCmdImpl-->param-->{}",param);

//        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
//        runtimeCompute.startRuntime();
        long execStartTime = System.currentTimeMillis();

        JSONArray dataArray = param.getJSONArray("data");
        JSONArray succesIdArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();
        JSONArray errArray = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {

            JSONObject dataJo = dataArray.getJSONObject(i);
            JSONObject oldJo = dataJo.getJSONObject("DL_B_PUR_IN");
            JSONArray purInItemArray = dataJo.getJSONArray("DL_B_PUR_IN_ITEM");

            Long billnoid = oldJo.getLong("ID");

            JSONObject stateObj = new JSONObject();
            Long objid = oldJo.getLong("OBJID");  //返回的ID
            int state = oldJo.getIntValue("STATE");//执行步骤

            try {

                JSONObject fixColumn = dataConversion(oldJo, purInItemArray);
                User user = postUserEvent.getUser(UserInformation.USER_NAME);
                JSONObject resultJson = new JSONObject();
                resultJson.put("objid", -1);
                resultJson.put("fixcolumn", fixColumn);
                resultJson.put("table", "DL_B_PUR_IN");
                accesLogger.info("WmsOrderInSaveCmdImpl--resultJson_save-->{}",resultJson);
//                log.info("保存resultJson==>" + resultJson.toString());
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("dlOrderIn", new HashMap(16));
                event.put("param", resultJson);
                querySession.setEvent(event);
                //1.调用保存服务
                if (0 == state) {

                    JSONObject retJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
                    accesLogger.info("WmsOrderInSaveCmdImpl--retJo-->{}",retJo);
                    if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                        throw new NDSException("保存失败:" + retJo.get("message") + retJo.get("error") + retJo.get("data"));
                    }
                    objid = retJo.getLong("objid");
                    if (objid == null) {
                        JSONObject retData = retJo.getJSONObject("data");
                        objid = retData.getLong("objid");
                    }
                    state = 1;
                    stateObj.put("objid", objid);
                    stateObj.put("state", state);

                }
                queryDataArray.add(resultJson);
                //2.提交服务
                if (1 == state) {

                    resultJson.put("objid", objid);
                    accesLogger.info("WmsOrderInSaveCmdImpl--resultJson_submit-->{}",resultJson);
//                    log.info("提交resultJson==>" + resultJson.toString());
                    event.put("param", resultJson);
                    querySession.setEvent(event);
                    JSONObject subJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "submit");
                    accesLogger.info("WmsOrderInSaveCmdImpl--subJo-->{}",subJo);
                    if (subJo.get("code") != null && (int) subJo.get("code") < 0) {
                        throw new NDSException("提交失败:" + subJo.get("message") + subJo.get("error") + subJo.get("data"));
                    }
                    state = 2;
                    stateObj.put("state", state);
                    stateObj.put("objid", objid);

                }
                //3.验收服务
                accesLogger.info("WmsOrderInSaveCmdImpl--resultJson_accept-->{}",resultJson);
//                log.info("验收resultJson==>" + resultJson.toString());
                resultJson.put("objid", objid);
                event.setParameter("command", "com.jackrain.nea.dl.pur.api.stock.PurStockAccepteStatusCmd:1.0:dl");
                event.setParameter("table", "DL_B_PUR_IN");
                event.setParameter("webaction", "PUR_IN_ACCEPT_SINGLE");
                event.put("param", resultJson);
                querySession.setEvent(event);
                JSONObject accJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "webaction");
                accesLogger.info("WmsOrderInSaveCmdImpl--accJo-->{}",accJo);

                if (accJo.get("code") != null && (int) accJo.get("code") < 0) {
                    throw new NDSException("验收失败:" + accJo.get("message") + accJo.get("error") + accJo.get("data"));
                }
                state = 3;
                stateObj.put("state", state);
                stateObj.put("id", billnoid);
                stateObj.put("objid", objid);
                succesIdArray.add(stateObj);

            } catch (Exception e) {

                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("id", billnoid);
                errrobj.put("state", state);
                errrobj.put("objid", objid);

                errArray.add(errrobj);
            }

        }

        if (errArray.size() > 0) {
            vh.put("error", errArray);
            vh.put("success", succesIdArray);
            vh.put("code", -1);
        } else {
            vh.put("success", succesIdArray);
            vh.put("code", 0);
        }
        vh.put("queryDataArray",queryDataArray);
//        Double spendTime = runtimeCompute.endRuntime();
        long execEndTime = System.currentTimeMillis();
        long spendTime=execEndTime-execStartTime;
        vh.put("spendtime", spendTime);
//        log.debug("---------采购入库执行时间--------->>" + spendTime);

        return vh;

    }

    /**
     * 数据整合
     *
     * @param oldJo          主表数据
     * @param purInItemArray 子表数据
     * @return JSONObject
     */
    public JSONObject dataConversion(JSONObject oldJo, JSONArray purInItemArray) {


        JSONObject newJo = new JSONObject();
        String billno = oldJo.getString("BILL_NO");
        newJo.put("ORDER_BILL_NO", billno);
//        JSONObject jsonObject = es(billno);
//        List<Long> longs = convertQLUtil.selectId(jsonObject.toString());
//        if (null != longs && longs.size() > 0) {
//            Long bill_ID = longs.get(0);
//            JSONObject source = billdata(jsonObject);
//            String bill_type = source.getString("BILL_TYPE");
//            newJo.put("ORDER_BILL_ID", bill_ID);
//            newJo.put("BILL_TYPE", bill_type);
//
//        } else {
//            throw new NDSException(billno + "单据编号查询不到对应的ID和BILL_TYPE");
//        }

        WmsOrderInMapper wmsOrderInMapper = ApplicationContextHandle.getBean(WmsOrderInMapper.class);
        HashMap orderMap = wmsOrderInMapper.selectIdType(billno);
        if (orderMap != null) {

            Long billId = TypeUtils.castToLong(orderMap.get("ID"));
            String billType = TypeUtils.castToString(orderMap.get("BILL_TYPE"));
            newJo.put("ORDER_BILL_ID", billId);
            newJo.put("BILL_TYPE", billType);
        } else {
            throw new NDSException(billno + "单据编号查询不到对应的ID和BILL_TYPE");
        }
        newJo.put("SOURCE_BILL_NO", oldJo.getString("WMS_BILL_NO"));
        newJo.put("OUT_BILL_ID", oldJo.getString("OUT_BILL_ID"));
        newJo.put("BILL_DATE", dateToStrLong(oldJo.getDate("DATE_IN")));
        newJo.put("CP_C_SUPPLIER_ECODE", oldJo.getString("ORIG_ECODE"));
        newJo.put("WMS_IN", "Y");

        String origecode = oldJo.getString("ORIG_ECODE");
        JSONObject whereJo1 = new JSONObject();
        whereJo1.put("ECODE", origecode);
        JSONObject cpmap1 = postQueryEvemt.queryCP("CP_C_SUPPLIER", "ID", whereJo1);
        if (cpmap1 == null) {
            throw new NDSException(origecode + "发货编码查不到对应的供应商ID！");
        }
        Long supploerid = TypeUtils.castToLong(cpmap1.getLong("ID"));
        newJo.put("CP_C_SUPPLIER_ID", supploerid);

        String destecode = oldJo.getString("DEST_ECODE");
        JSONObject whereJo2 = new JSONObject();
        whereJo2.put("ECODE", destecode);
        JSONObject cpmap2 = postQueryEvemt.queryCP("CP_C_STORE", "ID", whereJo2);
        if (cpmap2 == null || cpmap2.get("ID") == null) {
            throw new NDSException(destecode + "收货编码查不到对应的店仓ID！");
        }
        Long cpstoreid = cpmap2.getLong("ID");
        newJo.put("CP_C_STORE_ID", cpstoreid);
        newJo.put("REMARK", oldJo.getString("REMARK"));
        newJo.put("OWNERENAME", oldJo.getString("OWNER_ENAME"));
        newJo.put("OWNERNAME", oldJo.getString("OWNER_NAME"));

        JSONObject whereJo3 = new JSONObject();
        whereJo3.put("NAME", UserInformation.USER_NAME);
        JSONObject cpmap3 = postQueryEvemt.queryCP("USERS", "ID", whereJo3);
        if (cpmap3 == null) {
            throw new NDSException(UserInformation.USER_NAME + "查不到对应的用户信息！");
        }
        String ownerid = cpmap3.getString("ID");
        newJo.put("OWNERID", ownerid);
        newJo.put("MODIFIERID", ownerid);
        newJo.put("MODIFIERENAME", oldJo.getString("MODIFIER_ENAME"));
        newJo.put("MODIFIERNAME", oldJo.getString("MODIFIER_NAME"));
        newJo.put("isWMSCheck", "N");

        JSONArray itemArray = new JSONArray();
        for (int a = 0; a < purInItemArray.size(); a++) {

            JSONObject oldItemJo = purInItemArray.getJSONObject(a);
            JSONObject newItemJo = new JSONObject();
            String skuecode = oldItemJo.getString("SKU");
            JSONObject whereJo5 = new JSONObject();
            whereJo5.put("ECODE", skuecode);
            whereJo5.put("CP_C_DISTRIB_ID", "0");
            JSONObject cpmap5 = postQueryEvemt.queryCP("PS_C_SKU", "ID", whereJo5);
            if (cpmap5 == null) {
                throw new NDSException(skuecode + "条码编码查询不到对应的条码ID！");
            }
            Long skuId = TypeUtils.castToLong(cpmap5.getLong("ID"));
            newItemJo.put("PS_C_SKU_ID", skuId);
            newItemJo.put("PS_C_SKU_ECODE", skuecode);
            newItemJo.put("QTY_BILL", oldItemJo.getString("QTY_IN"));
            newItemJo.put("QTY_IN", oldItemJo.getString("QTY_IN"));
            itemArray.add(newItemJo);
        }

        JSONObject fixColumn = new JSONObject();
        fixColumn.put("DL_B_PUR_IN", newJo);
        fixColumn.put("DL_B_PUR_IN_ITEM", itemArray);

        return fixColumn;

    }

    /**
     * ES查询
     *
     * @param billNo 单据编号
     * @return id
     */
    public JSONObject es(String billNo) {
        JSONObject bill_no = esUtil.generateMatch("BILL_NO", billNo);
        List<JSONObject> terms = esUtil.packageTerm(bill_no);
        String esIndex = pconf.getProperty("DL_B_PUR_IN");
        JSONObject jsonObject = null;
        try {
            jsonObject = esUtil.searchAllDataByTerms(esIndex,
                    esIndex, "1", "10000", terms);
            log.debug("es_jsonObject->" + jsonObject);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }

    private JSONObject billdata(JSONObject esData) {
        JSONObject hits = esData.getJSONObject("hits");
        JSONArray hitsArray = hits.getJSONArray("hits");
        JSONObject sourceJson = hitsArray.getJSONObject(0);
        JSONObject source = sourceJson.getJSONObject("_source");

        return source;
    }

    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }

}